// 引入获取对象
var mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://127.0.0.1:27017' //数据库地址
var dbName = 'yimaiduo' //链接库名


// mongo("find", "user", { name: 1, age: 2 }, function (res) {
// console.log(res) 
// })
// 查找
var find = function (client, collection, selector, callback) {
  collection.find(selector).toArray(function (err, result) {
    if (err) throw err;
    console.log("查找成功")
    callback(result)
    client.close()//释放数据库连接
  })
}
// 增加一个
var insert = function (client, collection, selector, callback) {
  collection.insertOne(selector, function (err, result) {
    if (err) throw err;
    console.log("添加成功")
    callback(result.result)//{result:{ok:1,n:1}}
    client.close()
  })
}
// 删除一个
var del = function (client, collection, selector, callback) {
  collection.deleteOne(selector, function (err, result) {
    if (err) throw err;
    console.log("删除成功")
    callback(result.result)//{result:{ok:1,n:1}}
    client.close()
  })
}
// 修改一个
var update = function (client, collection, selector, callback) {
  collection.updateOne(selector[0], { $set: selector[1] }, function (err, result) {
    if (err) throw err;
    console.log("修改成功")
    callback(result.result)//{result:{ok:1,n:1}}
    client.close()
  })
}
// 删除多个
var delMany = function (client, collection, selector, callback) {
  collection.deleteMany(selector, function (err, result) {
    if (err) throw err;
    console.log("删除成功")
    callback(result.result)//{result:{ok:1,n:1}}
    client.close()
  })
}
// 增加多个
var insertMany = function (client, collection, selector, callback) {
  collection.insertMany(selector, function (err, result) {
    if (err) throw err;
    console.log("添加成功")
    callback(result.result)//{result:{ok:1,n:1}}
    client.close()
  })
}
// 修改多个
var updateMany = function (client, collection, selector, callback) {
  collection.updateMany(selector[0], { $set: selector[1] }, function (err, result) {
    if (err) throw err;
    console.log("修改成功")
    callback(result.result)//{result:{ok:1,n:1}}
    client.close()
  })
}

var methodType = {
  find: find, //查找
  insert: insert,//添加单个
  del: del,//删除一个
  update: update,//修改一个
  delMany: delMany,//删除多个
  insertMany: insertMany,//增加多个
  updateMany: updateMany//修改多个
}
module.exports = function (type, collections, selector, callback) {

  MongoClient.connect(url, function (err, client) {
    var db = client.db(dbName) //链接库名
    var collection = db.collection(collections) //连接表
    // methodType["insert"]
    methodType[type](client, collection, selector, callback)
  })

}


